package au.edu.anu.club.cs.sql;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TeamLocationDataSource {
	private SQLiteDatabase db;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.TEAMID,
									MySQLiteHelper.LATITUDE,
									MySQLiteHelper.LONGITUDE,
									MySQLiteHelper.TIME};
	
	public TeamLocationDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
		db = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public boolean createTeamLocation(long TeamID, double Latitude, double Longitude, long Time) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.TEAMID, TeamID);
		values.put(MySQLiteHelper.LATITUDE, Latitude);
		values.put(MySQLiteHelper.LONGITUDE, Longitude);
		values.put(MySQLiteHelper.TIME, Time);
		
		long insertID = db.insert(MySQLiteHelper.TABLE_ANUIB_TEAMLOCATIONS, null, values);
		//Cursor cursor = db.query(MySQLiteHelper.TABLE_ANUIB_TEAMLOCATIONS,
		//		allColumns, MySQLiteHelper.TEAMID + " = " + insertID, null, null, null, null);
		//TeamLocation newTeamLocation = cursorToTeamLocation(cursor);
		//cursor.close();
		return insertID != -1; //newTeamLocation;
	}
	
	public List<TeamLocation> getAllTeamLocations() {
		List<TeamLocation> teams = new ArrayList<TeamLocation>();
		
		Cursor cursor = db.query(MySQLiteHelper.TABLE_ANUIB_TEAMLOCATIONS,
				allColumns, null, null, null, null, MySQLiteHelper.TEAMID + " ASC, " + MySQLiteHelper.TIME + " ASC");
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			TeamLocation team = cursorToTeamLocation(cursor);
			teams.add(team);
			cursor.moveToNext();
		}
		cursor.close();
		return teams;
	}
	
	private TeamLocation cursorToTeamLocation(Cursor cursor) {
		TeamLocation team = new TeamLocation();
		team.setTeamID(cursor.getLong(0));
		team.setLatitude(cursor.getDouble(1));
		team.setLongitude(cursor.getDouble(2));
		team.setTime(cursor.getLong(3));
		return team;
	}
}
